using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Joystick : MonoBehaviour,IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    [SerializeField] Image backgroundImage;
    [SerializeField] Image handleImage;
    private float handleRange = 100;
    private float deadZone = 20;
    
    private bool isDragging = false;
    private Vector2 basePoint;


    void Start()
    {
        basePoint = backgroundImage.transform.localPosition;
    }

    // Update is called once per frame
    void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");
        GameManager.Instance.MovementValue = new Vector3(horizontalInput, verticalInput, 0);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        isDragging = true;
        backgroundImage.rectTransform.anchoredPosition = eventData.position;
        basePoint = eventData.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (isDragging)
        {
            Vector2 value = (eventData.position - basePoint);
            if (value.magnitude < handleRange)
            {
                handleImage.rectTransform.anchoredPosition = value;
            }
            else
            {
                handleImage.rectTransform.anchoredPosition = value.normalized * handleRange;
            }

            GameManager.Instance.MovementValue = value.magnitude > deadZone? value : Vector2.zero;
        }
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        isDragging = false;
        backgroundImage.rectTransform.anchoredPosition = new Vector2(540, 360);
        handleImage.rectTransform.anchoredPosition = Vector2.zero;
        
        basePoint = backgroundImage.transform.localPosition;
        GameManager.Instance.MovementValue = Vector2.zero;
        
    }
}
